const OT = {
	Proc: "/DataManager/Proc",
	ProcAddSet: "/DataManager/ProcAddSet",
	ProcSet: "/DataManager/ProcSet"
}

const FileServer = "https://Langchur.abc5g.com/";
const ServerUrl = "https://Langchur.abc5g.com/apis/"
const AuthCode = "1655883451884";




class PostData {
	constructor() {
		this.data = [];
	}

	dataFormat(value) {

		// console.log('dataFormat == value', value)
		try {
			return value.toString()
				.replace(/\+/g, "%2b")
				.replace(/=/g, "%3d")
				.replace(/&/g, "%26")
				.replace(/'/g, '$*$*$')
				.replace(/\\/g, '$!$!$')
				.replace(/"/g, '$@$@$')
				.replace(/\n\r/g, "\\n\\r")
				.replace(/\r\n/g, "\\r\\n")
				.replace(/\r/g, "\\r")
				.replace(/\n/g, "\\n");
		} catch (e) {
			console.log("PostData.dataFormat ==> 数据转换失败：");
			console.log(`value=${value.toString()}`);
			console.log("");
			return "";
		}
	}

	add(key, value) {

		let resultData = {};
		try {
			let tmp = '{ "' + key + '": "' + this.dataFormat(value) + '" }';
			resultData = JSON.parse(tmp);
		} catch (e) {
			console.log("PostData.add ==> 字符串转换JSON失败：");
			console.log(`key=${key}, value=${value.toString()}`);
			console.log(e);
			console.log("");
		}

		this.data.push(resultData);
	}

	addItem(item) {
		for (let key in item) {
			//console.log(key + ':' + item[key]);
			item[key] = this.dataFormat(item[key]);
		}

		this.data.push(item);
	}

	toString() {
		try {
			let result = JSON.stringify(this.data);
			result = result.replace(/"/g, "'"); //.replace(/###/g, '"');
			return result;
		} catch (e) {
			console.log("PostData.toString ==> JSON转换字符串失败：");
			console.log(e);
			console.log("");
		}

		return ""
	}
}

// 校验：是否是字符串
function isString(value) {
	return typeof value === 'string';
}
// 校验：是否为空
function isEmpty(value = null, clearSpace = false) {
	// 对常见的“非”值(不包含bool型)，直接返回原来值
	const empty = [null, undefined, NaN, ""]
	if (empty.includes(value)) return true

	// 清理空格、制表符后再校验
	if (isString(value) && clearSpace) {
		return value.replace(/\s+/g, '').length == 0
	}

	return false
}
// 校验：是否为空对象
function isEmptyObj(value){
	return [null, undefined].includes(value) ? true : Object.keys(value).length == 0;
}
// 校验：是否是Number类型
function isNumber(value, isAbsolute = true){
	if(isNaN(value / 1)){
		return false
	}

	// 强类型判断，入参必须是Number类型
	if(isAbsolute){
		return typeof value === 'number';
	}
	
	return true
}
// 校验：非值校验(多值)
function isEmptys(values, clearSpace = false){
	if (values instanceof Array) {
	  return !values.length || values.some(value => isEmpty(value, clearSpace))
	}
	return true
}
// 校验：是否是boolean类型
function isBoolean(value){
	typeof value === 'boolean';
}
// 校验：是否是Array
function isArray(value){
	value instanceof Array;
}
// 校验：是否是null
function isNull(value){
	value === null;
}
// 校验：是否是undefined
function isUnde(value){
	value === void 0;
}
// 获取一个uuid
function getUuid() {
	return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
		const r = Math.random() * 16 | 0;
		const v = c === 'x' ? r : (r & 0x3 | 0x8);
		return v.toString(16);
	})
}
// 返回一个范围之间的随机数
function random(min, max) {
	if (min >= 0 && max > 0 && max >= min) {
		let gab = max - min + 1;
		return Math.floor(Math.random() * gab + min);
	} else {
		return 0;
	}
}
// 数字格式转化：String => Number,如果参数不可转，返回0
function toNumber(str){
	return isNumber(str, false) ? parseInt(str) : 0;
}
// 时间格式转换
function dateFormat(val = null, format = "YYYY-MM-DD"){

	if (isEmpty(val) || isEmpty(format)) return val;
	if (typeof format !== 'string') return val;
	
	// const system = uni.getSystemInfoSync()
	// if (typeof val === 'string'){
	// 	if(system.osName === 'ios'){
	// 		val = val.replace(' ', 'T');
	// 	} else {
	// 		val = val.replace('T', ' ');
	// 	}
	// }
  
	try {
	  let date = new Date(val);
	  const fullYear = date.getFullYear(),
		month = date.getMonth() + 1,
		dateday = date.getDate(),
		hours = date.getHours(),
		minutes = date.getMinutes(),
		seconds = date.getSeconds()
  
	  const fm = {
		YYYY: fullYear,
		yyyy: fullYear,
		YYY: fullYear,
		yyy: fullYear,
		YY: fullYear.toString().padStart(2, '0'),
		yy: fullYear.toString().padStart(2, '0'),
		Y: fullYear % 100,
		y: fullYear % 100,
		MM: month.toString().padStart(2, '0'),
		M: month,
		DD: dateday.toString().padStart(2, '0'),
		dd: dateday.toString().padStart(2, '0'),
		D: dateday,
		d: dateday,
		HH: hours.toString().padStart(2, '0'),
		hh: hours.toString().padStart(2, '0'),
		H: hours,
		h: hours,
		mm: minutes.toString().padStart(2, '0'),
		m: minutes,
		ss: seconds.toString().padStart(2, '0'),
		s: seconds
	  }
  
	  let res = format;
	  for (let key in fm) {
		res = res.replace(new RegExp(key, 'g'), fm[key]);
	  }
  
	  return res;
	} catch (e) {
	  console.log(e)
	  return val;
	}
}
// ==pivotJson
function pivotJson(json, columnName, commondColumn,deep) {
	var temp = []; 
	var orgJson = [];
	if (deep) {
		orgJson = JSON.parse(JSON.stringify(json));
	} else {
		orgJson = json;
	}
	for (var i = 0; i < orgJson.length; i++) {
		var exist = false;
		for (var j = 0; j < temp.length; j++) {
			//console.log(temp[j]["title"] +":"+ json[i][columnName]);
			if (temp[j]["title"] == orgJson[i][columnName]) {
				exist = true;
				//console.log(temp[j]["title"]);
				temp[j]["items"].push(orgJson[i]);
				break;
			} else {
				exist = false;
			}
		}
		if (!exist) {
			var data = {};
			if (typeof (commondColumn) != 'undefined') {
				for (var k = 0; k < commondColumn.length; k++) {
					data[commondColumn[k]] = orgJson[i][commondColumn[k]];
				}
			}
			temp.push({
				"title": orgJson[i][columnName],
				"data": data,
				"items": [orgJson[i]]
			})
			//console.log(data);
		}
	}
	var result = [];
	for (var i = 0; i < temp.length; i++) {
		temp[i].data.items = temp[i].items;
		result.push(temp[i].data);
	}
	return result;
}
function unpivotJson(json,deep) {
	var temp = [];
	var orgJson = [];
	if (deep) {
		orgJson = JSON.parse(JSON.stringify(json));
	} else {
		orgJson = json;
	}
	for (var i = 0; i < orgJson.length; i++) {
		for (var j = 0; j < orgJson[i].items.length; j++) { 
			temp.push(orgJson[i].items[j]); 
		}
	}
	return temp;
}
// 解构请求结果
function deconResponse(resp, defaultVal) {
	if(resp && resp.data && resp.data.tables){
		return resp.data.tables;
	}

	if(resp && resp.data && resp.data.table){
		return resp.data.table;
	}
	
	return defaultVal;
}
// 同步设置Storage数据
function setStorageInfo(key, value){
	new Promise((resolve, reject) => {
		api.setStorage({
			key:key,
			data:value,
			encrypt:false,
			success:function(res){
				resolve(res)
			},
			fail:function(res){
				reject(res)
			},
			complete:function(res){
				
			},
		})
	}).then((res) => {
		// 设置成功
	}).catch(err => {
		// 设置失败
		console.log("ktlapi setStorageInfo 存储报错：")
		console.log(err);
		console.log("");
	})
}
// 同步获取Storage数据
function getStorageInfo(key, call){

	// 获取用户数据
	api.getStorage({
		key: key,
		encrypt: false,
		success:function(res){
			// 获取成功
			call && call(res)
		},
		fail:function(err){
			console.log("ktlapi getStorageInfo 获取数据报错：")
			console.log(err);
			console.log("");
			
		},
		complete:function(res){
			
		},
	})
}
// 参数格式化
function formatQuery(params = {}){
	let query = [ "__v=1" ]
	for(let key in params){
		query.push(`&${key}=${params[key]}`)
	}
	return query.join("").replace('__v=1&', '')
}

function treeJson(json, id, pid) {

	let data = JSON.parse(JSON.stringify(json));
	if (!data || !data.length) return [];
	let targetData = [];                    //存储数据的容器(返回)
	let records = {};
	let itemLength = data.length;           //数据集合的个数
	for (let i = 0; i < itemLength; i++) {
		let o = data[i];
		records[o[id]] = o;
	}
	for (let i = 0; i < itemLength; i++) {
		let currentData = data[i];
		let parentData = records[currentData[pid]];
		if (!parentData) {
			targetData.push(currentData);
			continue;
		}
		parentData.children = parentData.children || [];
		parentData.children.push(currentData);
	}
	return targetData;
}


function pageJson(json, currentPage, pagePercount) {
	 
	for (var i = 0; i < json.length; i++) {
		json[i]["ShowInPage"] = Math.floor(i / pagePercount) + 1;
		json[i]["IsInPage"] = false;
		if (json[i]["ShowInPage"] == currentPage) {
			json[i]["IsInPage"] = true;
		}
	}
	return json;
}
 

function distinctJson(json, key, value) {
	var temp = [];
	temp.push({ "Key": 0, "Value": "未选择" })
	for (var i = 0; i < json.length; i++) { 
		var exist_grade = false;
		for (var j = 0; j < temp.length; j++) {
			if (temp[j]["Key"] == json[i][key]) {
				exist_grade = true;
				break;
			}
		}
		if (!exist_grade) { 
			temp.push({ "Key": json[i][key], "Value": json[i][value] });
		}
	}
	return temp;
}


function childJson(json, columnValue, columnLabel, deep) {
	var temp = [];
	var orgJson = [];
	if (deep) {
		orgJson = JSON.parse(JSON.stringify(json));
	} else {
		orgJson = json;
	}
	for (var i = 0; i < orgJson.length; i++) {
		var exist = false;
		for (var j = 0; j < temp.length; j++) {
			//console.log(temp[j]["title"] +":"+ json[i][columnName]);
			if (temp[j]["value"] == orgJson[i][columnValue]) {
				exist = true;
				//console.log(temp[j]["title"]);
				temp[j]["children"].push(orgJson[i]);
				break;
			} else {
				exist = false;
			}
		}
		if (!exist) {
			var data = {};
			if (typeof (commondColumn) != 'undefined') {
				data[commondColumn[k]] = orgJson[i][columnLabel];
			}
			temp.push({
				"value": orgJson[i][columnValue],
				"label": orgJson[i][columnLabel],
				"children": [orgJson[i]]
			}) 
		}
	}
	return temp;
}

// 显示进度提示框



function showProgress(json){ 
	var con = typeof jQuery == 'undefined' ? $k : $;
	var title = '数据加载中'
	try{
		if(typeof(json["title"]) != 'undefined'){
			title = json["title"];
		}
	}catch(e){} 
	var existfc = false;
	if(con("#processfloat") && void 0 != con("#processfloat").length && con("#processfloat").length != 0){
		existfc = true;
	} 
	var html = '';  
	if(!existfc){
		html += '<div style="height:100%;width:100%; background-color:transparent; position:fixed;top:0px;left:0px;z-index:9999;" id="processfloat">';
		html += '<div style="background-color:#eee;width: 150px;height: 150px;position: absolute;top: calc(50% - 75px);left: calc(50% - 75px);border-radius: 20px;">';
		html += '<div style="width:100%;height:100px;margin-top:10px;text-align:center;"> ';
		if(json["image"]){
			html += '<img onclick="hideProgress();" style="width:100px; height:100px;margin: auto;" src="'+json["image"]+'" />';
		}else{
            var dirpathLen;
            if((api.appVersion+'').indexOf('00.') != -1){
                dirpathLen = location.pathname.split(api.appId)[1].split('\/').length - 1;
            }else{
                try{
                    dirpathLen = location.pathname.split('widget')[1].split('\/').length - 1;
                }catch(e){
                    dirpathLen = location.pathname.split('A2178708584713420804')[1].split('\/').length - 1;
                }
            }
           
            var relativePath = '';
            for(var i = 0; i < dirpathLen - 1; i++){
                relativePath += '../';
            }
           
			html += '<img onclick="hideProgress();" style="width:100px; height:100px;margin: auto;" src="' + relativePath + 'image/X5fly.gif" />';
		}
		html += '</div>';
		html += '<div id="processTitle" class="processdiv" style="width: 100%;height: 20px;margin-top:10px;font-size: 14px;letter-spacing:2px;font-weight: bold;text-align: center;">';
		
		html += '<span style="color:#000 !important;">'+title+'</span>';
		
		html += '</div>';
		html += '</div>';
		html += '</div>';
		con("body").prepend(html);
	}else{
		var titlehtml = '';
		//for(var i=0;i<title.length;i++){
			titlehtml += '<span style="color:#000 !important;">'+title+'</span>';
		//}
		con("#processTitle").html(titlehtml);
	}  
}

function hideProgress(){
	var con = typeof jQuery == 'undefined' ? $k : $;
	con("#processfloat").remove(); 
}
 
var AIBase = {
	"deepseek":{
		"api_key":"sk-3779c5636c7d45f3a9559d648dd5d0e0",
		"api_url":"https://api.deepseek.com/chat/completions",
		"modelId":"deepseek-chat"
	},
	"doubao":{
		"api_key":"ccbf443f-fb4d-4e12-b336-caedee752601",
		"api_url":"https://ark.cn-beijing.volces.com/api/v3/chat/completions",
		"modelId":"ep-20250217165633-9269x"
	}
}


function AIAPI(message,proc,succ,err){ 

	var useAI = "doubao";

	// 豆包
	var api_key = AIBase[useAI]["api_key"];  
	var api_url = AIBase[useAI]["api_url"];  
	var modelId = AIBase[useAI]["modelId"];  

	// deepseek
	// var api_key = "sk-3779c5636c7d45f3a9559d648dd5d0e0";  
	// var api_url = "https://api.deepseek.com/chat/completions";
	// var modelId = "deepseek-chat";

	$.ajax({
		url: api_url,
		type: 'POST',
		contentType: 'application/json',
		headers:{
			"Authorization":"Bearer " + api_key
		}, 
		data: JSON.stringify({
				"model":modelId, 
				"stream":true,
				"messages":message,
				"stream_options":{"include_usage":true}
			}),
		xhr: function () {
			var xhr = new XMLHttpRequest();
			xhr.onreadystatechange = function () {
				if (xhr.readyState > 2 && xhr.status === 200) {  
					// console.log('xhr.responseText', xhr.responseText);
					const newData = xhr.responseText; 
					const list = newData.split('\n');
					let respText = '';
					for(var i=0;i<list.length;i++){ 
						try{ 
							if(list[i].indexOf('[DONE]') == -1){
								var temp = JSON.parse(list[i].substring(6));
								// itemlist.push(temp); 
								for(var j=0;j<temp.choices.length;j++){
									respText += temp.choices[j].delta.content;
								}
							}
						}catch(e){
							console.error(list[i])
						}
					} 

					proc && proc(respText); 
				}
			}; 
			return xhr;
		}, 
		success: function (data) { 
			console.log('完整请求-------------------------------',data);
			const dataList = data.split('data:');
			if(dataList[dataList.length-1].includes('[DONE]')){
				const lastData = JSON.parse(dataList[dataList.length-2]);
				succ({
					AIName: useAI,
					Model: modelId,
					TokenInputCnt: lastData.usage.prompt_tokens,
					TokenOutCnt: lastData.usage.completion_tokens
				});
				return;
			}
			succ({});
		},
		error: function (error) {
			// 请求失败时的处理
			console.error('请求失败:', JSON.stringify(error));
			err && err(error);
		}
	})
}

// 请求方法封装 ==ktlapi
function ktlapi(options = {}) {

	// api 请求地址，默认使用proc
	let request_url = ServerUrl + OT.Proc;
	if(!isEmpty(options.url)){
		request_url = ServerUrl + options.url;
	} else {
		// 空值校验，如果为空值，默认使用proc
		if (!isEmpty(options.apiurl)){
			request_url = ServerUrl + options.apiurl;
		}
	}

	let body = {}
	if(!isEmpty(options.url) && options.url.indexOf('/DataManager/Proc')==-1){
		// console.log('自定义接口')
		if(!isEmptyObj(options.data)){ 
			body = { ...options.data } 
		}
	} else {
		// 参数传递 
		const params = new PostData()
		// console.log('通用接口')
		// console.log(JSON.stringify(options));
		if (!isEmptyObj(options.data)) {
			if (options.apiurl === OT.ProcAddSet) {
				// 数组，插入多条
				options.data.forEach(item => params.addItem(item))
			} 
			else {
				for (let key in options.data) {
					params.add(key, options.data[key])
				}
			}
		}

		body = {
			Name: options.name,
			AuthCode: AuthCode,
			Parameters: params.toString()
		}
	}

	console.log("请求地址："+request_url);
	console.log('请求参数：', JSON.stringify(body));

	return new Promise((resolve, reject) => {
		api.ajax({
			url: request_url,
			method: 'post',
			headers: {
				'Content-Type': 'application/json;charset=utf-8'
			},
			data: {
				body: body
			}
		}, function (ret, err) {
			if (ret) {
				resolve(ret)
			} else {
				try {
					// console.log(err.msg)
					api.showProgress({
						title: "提示",
						text: err.msg
					})
					setTimeout(function () {
						api.hideProgress()
					}, 2000);
				} catch (e) {
				}
				reject(err)
			}
		});
	})
}




function ktlConfirm(opts,callback){ 
	
	var customDialog = new CustomDialogBox(); 
	var pars = { 
		type:'custom',
		title:opts["title"],
		content: opts["html"],  
		callback: callback
	};
	if(typeof(opts["buttons"]) != 'undefined'){
		pars["buttons"] = opts["buttons"];
	}
	if(typeof(opts["topImg"]) != 'undefined'){
		pars["topImg"] = opts["topImg"];
	}
	if(typeof(opts["topText"]) != 'undefined'){
		pars["topText"] = opts["topText"];
	}
	if(typeof(opts["top"]) != 'undefined'){
		pars["top"] = opts["top"];
	}
	if(typeof(opts["left"]) != 'undefined'){
		pars["left"] = opts["left"];
	}
	if(typeof(opts["right"]) != 'undefined'){
		pars["right"] = opts["right"];
	}
	//alert(JSON.stringify(pars));
   
	customDialog.open(pars); 
	
}

var CustomDialogBoxIndex = 999999;
    // 自定义弹窗
var CustomDialogBox = function(){ 
	var result = {
		option: {
			type:'custom',
			title:'消息提示',
			msg:'提示内容',
			buttons:["取消","确定"],
			content:'',
			top:50,
			left:200,
			right:200,
			topImg:'',
			topText:'',
			height:'auto'
		},
		bindData: function(){
			var args = arguments;
			var _default = this.option;
			if(args.length > 0){
				var initdata = function(arg){
				
					if(arg[0] && typeof arg[0] == 'string'){ 
						_default["type"] = "message";
						_default["title"] = arg[0];
						
						if(arg[1] && typeof arg[1] == 'string'){
							_default["msg"] = arg[1];
						}
						
						if(arg[2] && typeof arg[2].constructor == Array){
							_default["buttons"] = arg[2];
						}
					} else if(arg[0] && arg[0].constructor == Object){
						for(var key in arg[0]){
							_default[key] = arg[0][key];
						}
						
						
						_default["type"] = arg[0]["type"] ? arg[0]["type"] : 'message';
					}
					
					if(arg[arg.length-1] && arg[arg.length-1].constructor == Function){
						_default["callback"] = arg[arg.length-1];
					}
				}
				
				if(args[0].constructor == Array){
					initdata(args[0]);
				} else {
					initdata([].slice.call(args));
				}
			}
		}
	};
	
	CustomDialogBoxIndex++;
	result.id = 'CustomDialogBox'+Math.random().toString().replace('.','');
	result.open = function(){
		
		var _this = this;
		_this.bindData([].slice.call(arguments));
		
		// 添加弹窗监听
		api.addEventListener({
			name: _this.id
		}, function(ret, err){
			// 移除监听
			api.removeEventListener({ name:_this.id });
			
			// 移除弹窗对象
			try{
				document.getElementById(_this.id).remove();
			}catch(e){
				console.log(e)
			}
			
			// 执行按键回调函数
			setTimeout(function(){                	
				ret.value.value = ret.value.index;
				_this.option.callback && _this.option.callback(ret.value, err);
			},200);
		});
		
		var param = _this.option;
			
		var zhezhaoceng = document.createElement('div');
		zhezhaoceng.setAttribute("id", _this.id);
		zhezhaoceng.setAttribute('style','position:fixed;top:0;left:0;right:0;bottom:0;z-index:'+CustomDialogBoxIndex+';background-color:rgba(0,0,0,0.5);overflow: scroll;');
		
		var html = '';
		if(param.type == "message"){
			html += '<div class="message-box" style="position: absolute;background-color:#fff;border-radius:4px;padding:10px;top:'+param.top+'px;left:'+param.left+'px;right:'+param.right+'px;height:'+param.height+'px">';
			
			var btns = '';
			for(var i = 0;i<param.buttons.length && i<2;i++){
				btns += '<div class="btn" style="display:inline-block;background-image:url(../image/btnrst.png);background-size: 100% 100%;width: 150px;height:50px;line-height:50px;font-size:20px;color:#fff;margin:0 20px;" onclick="api.sendEvent({ name:\''+_this.id+'\', extra:{ id:\''+_this.id+'\', index:'+i+' } });">'+param.buttons[i]+'</div>';
			}
			html += '<div class="title" style="text-align:center;height:50px;line-height: 50px;">'+param.title+'</div>'
			+'<div class="msg" style="text-align:center;height:140px;padding:5px;">'+param.msg+'</div>'
			+'<div class="bottons" style="text-align:center;">' + btns + '</div>';
			html += '</div>';
		}
		
		if(param.type == "custom"){
			
			//dev('弹窗：组装相对路径----开始');
			var dirpathLen;
			// console.log(location.pathname);
			if((api.appVersion+'').indexOf('00.') != -1){
				dirpathLen = location.pathname.split(api.appId)[1].split('\/').length - 1;
			}else{
				try{
					dirpathLen = location.pathname.split('widget')[1].split('\/').length - 1;
				}catch(e){
					dirpathLen = location.pathname.split('A2178708584713420804')[1].split('\/').length - 1;
				}
			}
			
			//dev('弹窗：location.pathname：'+location.pathname);
			
			var relativePath = '';
			for(var i = 0; i < dirpathLen - 1; i++){
				relativePath += '../';
			}
			//dev('弹窗：组装相对路径----结束');
			
			var topImgLib = [relativePath + "image/diabg.jpg", relativePath + "image/diabg1.jpg"];
			var topTextLib = [
				"Don't give up and don't give in. <br/>不要放弃，不要言败!",
				"Go for it! Just do it! <br/>加油!向前冲!做了再说!",
				"Better late than never. <br/>只要开始，虽晚不迟。",
				"A bold attempt is half success.<br/>勇敢的尝试是成功的一半。",
				"Do what you say,say what you do. <br/>做你说过的，说你能做的",
				"Zero in your target,and go for it. <br/>从零开始，勇往直前!",
				"Never, never, never, never give up. <br/>永远不要、不要、不要、不要放弃。",
				"There is only one me in this world. <br/>在这个世界上，我是独一无二的",
				"When it has is lost, brave to give up. <br/>当拥有已经是失去，就勇敢的放弃。"
			]; 
			html += '<div class="custom-box" style="position: absolute;overflow:hidden;top:'+param.top+'px;left:'+param.left+'px;right:'+param.right+'px;height:'+param.height+'px">';
			
			var useImg = '';
			var useText = '';
			
			if(param.topImg == ''){
				useImg = topImgLib[Math.floor((Math.random()*topImgLib.length))];
			}else{
				useImg = param.topImg;
			}
			if(param.topText == ''){
				useText = topTextLib[Math.floor((Math.random()*topTextLib.length))];
			}else{
				useText = param.topText;
			}
			//dev('弹窗：组装html---开始');
			html += '<div style="width:100%;background:#fff;border-radius:0px;overflow:hidden;">';
			html += '   <div style="border-top:1px solid transparent;width:100%;height:120px;background:url('+useImg+');background-size:100% 100%;">';
			html += '       <div style="color:rgba(255,255,255,0.7);width:90%;height:80px;margin-top:30px;margin-left:40px;margin-right:70px;font-size:14px;">'+useText+'</div>';
			html += '   </div>';
			html += '</div>';
			html += '<div style="width:100%;background:#fff;overflow:hidden;">';
			html += '   <div style="height:70px;margin-top:20px;background:url('+relativePath+'image/dialog_title_bg.png) no-repeat center;width:100%;background-size:contain;">';
			html += '      <div style="width:100%;font-weight: bold;font-size: 16px;text-align:center;color:rgba(255,255,255,0.9);padding-top:11px;">'+param.title+'</div>';
			html += '   </div>'; 
			html += '<div style="text-align:center;margin-top:20px;font-size:18px;color:#333;">'+param.content+'</div>';
			html += '   <div style="text-align:center;margin-top:40px;margin-bottom:30px;">';
			// console.log(param.content)
			for(var i = 0;i<param.buttons.length;i++){
				html += '<div onclick="api.sendEvent({ name:\''+_this.id+'\', extra:{ id:\''+_this.id+'\', index:'+i+' } });" style="display:inline-block;background-image:url('+relativePath+'image/btnrst.png);background-size: 100% 100%;width: 150px;height:50px;line-height:50px;font-size:20px;color:#fff;margin:5 20px;">'+param.buttons[i]+'</div>';
			}
			//dev('弹窗：组装html---结束');
			html += '   </div>';
			html += '</div>';
			html += '</div>';
		}
		zhezhaoceng.innerHTML = html;
		
		document.body.appendChild(zhezhaoceng);
		
	}
	result.close = function(){
		// 移除监听
		api.removeEventListener({ name: this.id });
		// 移除弹窗对象
		document.getElementById(this.id).remove();
	}
	
	return result;
}



function ktluser(opts) {
    return new initKtluser(opts);
}
function initKtluser(opts, isReset) { 
    var user = $api.getStorage("userinfo_mobile") || {};
    if (opts) {
        for (var key in opts) {
            user[key] = opts[key];
        }
    	
    	if(!isReset){
    		user["logintime"] = new Date();
    	}
        
        $api.setStorage("userinfo_mobile",user);
    }
    
    user["loginOff"] = function(){
        ktluser = null;
        $api.rmStorage("userinfo_mobile");
        $api.rmStorage("studycount"); 
    }
	
    user["setVal"] = function(key, val){
    	var _def = {};
    	_def[key] = val;
    	ktluser = initKtluser(_def, true);
    } 
    return user;
}
ktluser = new initKtluser(); 
